<?php

namespace ticket\modules\frontend\models;

use Yii;

/**
 * This is the model class for table "tk_coupon_log".
 *
 * @property int $id
 * @property int $oid 订单id
 * @property int $coupons_type 优惠券类型
 * @property string $coupon_id 优惠券id
 * @property string $couponname 优惠券名称
 * @property string $discount 折扣值
 * @property string $coupon_code 优惠券code
 * @property string $member_id 会员id
 * @property string $app_id 实例appId
 * @property string $use_time 使用时间
 * @property string $hexiao_result 核销结果
 */
class CouponLog extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'tk_coupon_log';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['oid', 'coupons_type'], 'integer'],
            [['use_time','post_data'], 'safe'],
            [['coupon_id', 'member_id'], 'string', 'max' => 64],
            [['couponname', 'discount', 'coupon_code', 'coupon_from', 'hexiao_result'], 'string', 'max' => 255],
            [['app_id'], 'string', 'max' => 32],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'oid' => 'Oid',
            'coupons_type' => 'Coupons Type',
            'coupon_id' => 'Coupon ID',
            'couponname' => 'Couponname',
            'discount' => 'Discount',
            'coupon_code' => 'Coupon Code',
            'coupon_from' => 'Coupon From',
            'member_id' => 'Member ID',
            'app_id' => 'App ID',
            'use_time' => 'Use Time',
            'hexiao_result' => 'Hexiao Result',
        ];
    }

    public static function addInfo($oid,$discount,$params,$result,$memberId = '',$coupon_from)
    {
        $model = new self();
        $data = [
            'CouponLog' => [
                'oid' => $oid,
                'coupons_type' => isset($params['coupons_type'])?$params['coupons_type']:'',
                'coupon_id' => isset($params['coupon_id'])?$params['coupon_id']:'',
                'couponname' => isset($params['coupon_name'])?$params['coupon_name']:'',
                'discount' => (string)$discount,
                'coupon_code' => isset($params['couponCode'])?$params['couponCode']:'',
                'member_id' => isset($params['member_id'])?$params['member_id']:$memberId,
                'app_id' => isset($params['appId'])?$params['appId']:'',
                'use_time' => date("Y-m-d H:i:s"),
                'hexiao_result' => $result,
                'coupon_from' => $coupon_from,
                'post_data' => json_encode($params,JSON_UNESCAPED_UNICODE),
            ]
        ];

        if ($model->load($data) and $model->validate()){
            if ($model->save(0)){
                return true;
            }
        }

        return false;
    }
}
